#include <iostream>
#include <stdio.h>
#include "torrent.h"
#include <signal.h>

using namespace std;

int main (int argc, char** argv)
{
	//block SIGPIPE
	sigset_t blocked;
	sigemptyset(&blocked);
	sigaddset(&blocked,SIGPIPE);
	sigprocmask(SIG_BLOCK,&blocked,NULL);

	// check args
	if (argc != 2)
	{
		printf("Incorrect Usage.\n");
		return -1;
	}

	// create the torrent
	Torrent *torrent = new Torrent(argv[1]);

	// NOTE: this will infinite loop if there are any pieces not being seeded by any peer
	while (torrent->GetDownloaded() != torrent->GetFileSize())
	{
		// get peers from trackers
		if (torrent->GetNumTrackers() < 1)
			break;
		printf("Contacting trackers(%i)...\n", torrent->GetNumTrackers());
		for (unsigned i = 0; i < torrent->GetNumTrackers(); i++)
		{
			// obtain a peer list from tracker
			if (torrent->GetTracker(i)->Connect())
			{
				torrent->GetTracker(i)->RequestPeers(50);
				torrent->GetTracker(i)->Disconnect();
			}
		}

		// obtain pieces from peers
		if (torrent->GetNumPeers() < 1)
			continue;
		printf("Contacting peers(%i)...\n", torrent->GetNumPeers());
		for (unsigned j = 0; j < torrent->GetNumPeers(); j++)
		{
			if (torrent->GetPeer(j)->Connect())
			{
				while (torrent->GetPeer(j)->DownloadNextPiece());
				torrent->GetPeer(j)->Disconnect();
			}
			if (torrent->GetDownloaded() == torrent->GetFileSize())
				break;
		}
	}

	// Print completion and exit
	printf("Download complete: %s\n", torrent->GetFileName().c_str());
	delete torrent;
	return 0;
}
